package dao;

import entites.Account;
import utils.DBUtils;
import utils.DateUtils;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2023/1/12 10:36
 * @copyright: 博为峰
 */
public class AccountDaoImpl implements AccountDao {
    @Override
    public int insert(Account account) {
        int i = -1;
        try (Connection conn = DBUtils.getConn();
             PreparedStatement preparedStatement = conn.prepareStatement("insert into account (name,balance,create_time,update_time) values (?,?,?,?)");
        ) {
            preparedStatement.setString(1, account.getName());
            preparedStatement.setInt(2, account.getBalance());
            preparedStatement.setTimestamp(3, DateUtils.getTimestamp());
            preparedStatement.setTimestamp(4, DateUtils.getTimestamp());
            i = preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throw new RuntimeException("插入账户异常");
        }
        return i;
    }

    @Override
    public int update(int money, String name, Connection conn) {
        int i = -1;
        try (PreparedStatement preparedStatement = conn.prepareStatement("update account set balance = balance + ? where name = ?");) {
            preparedStatement.setInt(1, money);
            preparedStatement.setString(2, name);
            i = preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException("更新账户异常");
        }
        return i;
    }
}
